// FunkyDog MailBundle - tags and keywords for Apple Mail 3.0
//    Copyright (C) 2008 saptarshi guha saptarshi.guha@gmail.com
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.


#import "AppleMail/Message.h"
#import "AppleMail/Library.h"
#import "Matador-FD.h"
#import "TagPaneViewOwner.h"
#include "FunkyDog.h"


@implementation TagPaneViewOwner
-(id)initWithMessage:(NSString *)m messId:(NSString *)n{
	self=[super init];
	if(self){
	//	NSLog(@"UID %u",n);
		[NSBundle loadNibNamed: @"special" owner: self];
		[m retain];
		if(message) [message release];
		message=m;
		messID=n;
		[self setInfoForMessage];
		//[self performSelector:@selector(setInfoForMessage) withObject:nil afterDelay:0.005];
	}
	return self;
}
-(void)setInfoForMessage{
	
	if( [ [[FunkySob sharedInstance] cachesystem] objectForKey:messID]){
		NSDictionary *plist=[ [[FunkySob sharedInstance] cachesystem] objectForKey:messID];
		if( [plist objectForKey:@"SGFDNotes"]){ [notesfield setStringValue:[plist objectForKey:@"SGFDNotes"]];}
		if( [plist objectForKey:@"SGFDTags"]){ [tokenfield setObjectValue:[plist objectForKey:@"SGFDTags"]];}
		if( [plist objectForKey:@"SGFDPriority"]){ 
			[priorityfield setIntValue:  [[plist objectForKey:@"SGFDPriority"] intValue]];
		}
	//	NSLog(@"Used cache");
	}else{
		
	NSFileHandle *f=[ NSFileHandle fileHandleForReadingAtPath: message];
	NSUInteger nt= [[ [NSNumber numberWithUnsignedInteger:NSUIntegerMax] stringValue] length];
	NSString *numberwithextras=[ [NSString alloc] initWithData:[f readDataOfLength:nt] 
														   encoding:NSUTF8StringEncoding];
	NSRange r_=[numberwithextras rangeOfString:@"\n"];
	NSUInteger numtoread=[[numberwithextras substringToIndex:r_.location] integerValue];
	wheretoread=1+r_.location+numtoread;
	NS_DURING
	//NSLog(@"Mess details: maxleng(%u), read(%@),locofnewline(%u),and where=%d",
	//	  nt,numberwithextras,numtoread,wheretoread);
	[f seekToFileOffset:wheretoread];
	NSDictionary *plist=[[ [NSString alloc] initWithData:[f readDataToEndOfFile] encoding: NSUTF8StringEncoding] propertyList];
	if( [plist objectForKey:@"SGFDNotes"]){ [notesfield setStringValue:[plist objectForKey:@"SGFDNotes"]];}
	if( [plist objectForKey:@"SGFDTags"]){ [tokenfield setObjectValue:[plist objectForKey:@"SGFDTags"]];}
	if( [plist objectForKey:@"SGFDPriority"]){ 
		[priorityfield setIntValue:  [[plist objectForKey:@"SGFDPriority"] intValue]];
	 }
		[[ [FunkySob sharedInstance] cachesystem] setObject:plist forKey:messID];
	[f closeFile];
	//	NSLog(@"Used file");
	NS_HANDLER
	NSLog(@"Error raised reading emlx file %@[%@]",message,localException);
	[f closeFile];
	NS_ENDHANDLER
	}

}
-(NSView*)tagpane{
	return tagpane;
}
- (NSArray *)tokenField:(NSTokenField *)tokenFieldArg completionsForSubstring:(NSString *)substring 
		   indexOfToken:(NSInteger)tokenIndex indexOfSelectedItem:(NSInteger  *)selectedIndex 
{
	NSSet *tags= [[ FunkySob sharedInstance] tags];
	NSArray *matchingtags=[[tags filteredSetUsingPredicate: [NSPredicate predicateWithFormat:@"SELF beginswith[cd] %@", substring]]
						   allObjects];
	return matchingtags;
}
-(void)dealloc{
	NSLog(@"TagView Manager being release");
	[message release];
	[super dealloc];
}
//Quirk - a single enter does not trigger the action, double enter does!
-(IBAction)tagsset:(id)sender{
	[[ FunkySob sharedInstance] updateTags: [sender objectValue]];
}
- (id)tokenField:(NSTokenField *)tokenField representedObjectForEditingString:(NSString *)editingString
{
	[[ FunkySob sharedInstance] updateTags: [NSArray arrayWithObject:editingString]];
	[self performSelector:@selector(updatematadorta) withObject:nil afterDelay:0.05];
	return editingString;
}
-(void)updatematadorta{
	[Matador_FD FDsetAttributeForFileAtPath:message  name:@"kMDItemKeywords" value:[tokenfield objectValue]];
	[self setPlistFileForMessage];
	
}
-(IBAction)noteset:(id)sender{
	[Matador_FD FDsetAttributeForFileAtPath:message  name:@"kMDItemComment" value:[sender  stringValue]];
	[self setPlistFileForMessage];
	
}
-(IBAction)prioset:(id)sender{
		[Matador_FD FDsetAttributeForFileAtPath:message name:@"kMDItemStarRating" 
										  value:[NSNumber numberWithInt:[sender intValue]]];
		[self setPlistFileForMessage];
	   
}
-(void)setPlistFileForMessage{
	//this might be slow..lets see on usage.

	NSFileHandle *f=[ NSFileHandle fileHandleForUpdatingAtPath: message];
		//At times, the plists string is entire email, whichs means wheretoread=0
	NSUInteger nt0= [[ [NSNumber numberWithUnsignedInteger:NSUIntegerMax] stringValue] length];
	NSString *numberwithextras=[ [NSString alloc] initWithData:[f readDataOfLength:nt0] 
													  encoding:NSUTF8StringEncoding];
	NSRange r_=[numberwithextras rangeOfString:@"\n"];
	NSUInteger numtoread=[[numberwithextras substringToIndex:r_.location] integerValue];
	wheretoread=1+r_.location+numtoread;
	[f seekToFileOffset:wheretoread];
	NSString *plists=[ [NSString alloc] initWithData:[f readDataToEndOfFile] encoding: NSUTF8StringEncoding] ;
	NSDictionary *plist=[plists propertyList];
	NSMutableDictionary *d=[NSMutableDictionary dictionaryWithDictionary:plist];
	NSString *nt=[notesfield stringValue];
	NSNumber* prio=[NSNumber numberWithInt:[priorityfield intValue]];
	NSArray *tags=[tokenfield objectValue];
	if(tags) {[d setObject:tags forKey:@"SGFDTags"]; }else{ [d removeObjectForKey:@"SGFDTags"];}
	if(nt) [d setObject:nt forKey:@"SGFDNotes"]; else  [d removeObjectForKey:@"SGFDNotes"];
	if(prio) {[d setObject:prio forKey:@"SGFDPriority"];} else [d removeObjectForKey:@"SGFDPriority"];
	[f seekToFileOffset:wheretoread];
	NSData *xmlData;
	NSString *error;

	xmlData = [NSPropertyListSerialization dataFromPropertyList:d
														 format:kCFPropertyListXMLFormat_v1_0
											   errorDescription:&error];
	[f writeData:xmlData];
	[f closeFile];
	[Matador_FD FDsetAttributeForFileAtPath:message  name:@"kMDItemKeywords" value:[tokenfield objectValue]];
	[[ [FunkySob sharedInstance] cachesystem] setObject:d forKey:messID];
	
	
}	

@end
